package org.charmsoft.tasks;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.charmsoft.dto.ClassesInSheet;
import org.charmsoft.dto.ClassesInWorkbook;
import org.charmsoft.error.ReturnCode;
import org.charmsoft.error.StatusCode;
import org.charmsoft.generator.ClassGenerator;
import org.charmsoft.generator.Generator;
import org.charmsoft.generator.SQLGenerator;
import org.charmsoft.utils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

public class GenerateTask implements Callable<StatusCode> {

    private static final Logger LOGGER = LoggerFactory.getLogger(GenerateTask.class);

    private static final String skipSheetName = "Template guide";

    private XSSFWorkbook workbook;

    private String workbookName;

    public GenerateTask(String workbookName, XSSFWorkbook workbook) {
        this.workbook = workbook;
        this.workbookName = workbookName;
    }
    @Override
    public StatusCode call() throws Exception {
        ClassesInWorkbook classesInWorkbook = new ClassesInWorkbook();
        classesInWorkbook.setWorkBookName(workbookName.substring(0,workbookName.indexOf('.')));
        classesInWorkbook.setProjectName(workbookName.substring(workbookName.lastIndexOf('-') + 1, workbookName.indexOf('.')));
        int workSheetNumber = workbook.getNumberOfSheets();
        List<HSSFSheet> sheets = new ArrayList<>();
        StatusCode statusCode = new StatusCode();
        Map<String, ClassesInSheet> classesInWorkbookMap = new HashMap<>();
        for (int i = 0; i < workSheetNumber; i++) {

            XSSFSheet sheet = workbook.getSheetAt(i);
            if(sheet.getProtect()){
                LOGGER.info(sheet.getSheetName() + " sheet is locked = " + sheet.getProtect());
                break;
            }
                // Remove empty rows
            ExcelUtils.deleteEmptyRow(sheet);
            int physicalRowNum = sheet.getPhysicalNumberOfRows();
            int rowCount = sheet.getLastRowNum();
            ClassesInSheet classesInSheet = ExcelUtils.getSheetClasses(sheet);
            classesInSheet.setWorksheetName(sheet.getSheetName());
            classesInWorkbookMap.put(sheet.getSheetName(), classesInSheet);
            LOGGER.info(classesInSheet.toString());
        }
        classesInWorkbook.setClassesInWorkbookMap(classesInWorkbookMap);
        Generator clg = new ClassGenerator(classesInWorkbook);
        clg.generate();
        Generator sqlg = new SQLGenerator(classesInWorkbook);
        sqlg.generate();
        statusCode.setMessage(String.valueOf(ReturnCode.valueOf(ReturnCode.CONVERTED.name())));
        return statusCode;
    }


}
